package com.css.filexml.server;

import com.alibaba.fastjson.JSON;
import com.css.filexml.model.MsgEntity;
import com.css.filexml.utils.XMLUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Xml报文落地服务
 *
 * @author 一朝风月
 * @date 2021/12/16 14:59
 */
@Service("FileXmlServer")
@Slf4j
public class FileXmlServer {
    /**
     * 文件存储路径
     */
    @Value("${filePath}")
    private String filePath;
    /**
     * 日志路径
     */
    @Value("${logPath}")
    private String logPath;
    /**
     * 日志文件名
     */
    @Value("${logFileName}")
    private String logFileName;

    /**
     * 处理消息
     *
     * @param message 消息
     */
    public void handleMessage(Message message) {
        String data = new String((byte[]) message.getPayload());
//        SendMsg msg = JSON.parseObject(data, SendMsg.class);
        MsgEntity msg = JSON.parseObject(data, MsgEntity.class);
        String filePathName = filePath + File.separator + msg.getUuid() + ".xml";
        XMLUtil.convertToXml(msg, filePathName);
        File fileOk = new File(filePathName + ".ok");
        if (new File(filePathName).exists()) {
            XMLUtil.convertToXml(msg, fileOk.getPath());
        }
        try {
            printLog(JSON.toJSONString(msg));
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

    /**
     * 记录日志
     *
     * @param msg 消息
     * @throws IOException 异常
     */
    private void printLog(String msg) throws IOException {
        File filePath = new File(logPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
            new File(logPath + File.separator + logFileName).createNewFile();
        }
        BufferedWriter out = new BufferedWriter(new FileWriter(logPath + File.separator + logFileName, true));
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
        out.write(currentTime + "\t" + msg + "\n");
        out.close();
    }
}